//
//  TSCVCGuideBizListPage.m
//  Tsc_IOS
//
//  Created by Rio on 15-9-24.
//  Copyright (c) 2015年 idream. All rights reserved.
//
// -- TODO 想买、想卖，抽象为string.xml
// xx TODO reuseCellId抽象到Constants中
// TODO 来回滑动几次后，有约束冲突（还未解决，不太好弄）
// -- TODO TSCVCSelectShop/Mall也照此规范进行修改



#import "TSCVCGuideBizListPage.h"
#import "TSCSDK.h"
#import "TSCVCCustomerWantBuyR.h"
#import "TSCVCReplyQA.h"
#import "TSCVCCustomerSpace.h"


@implementation TSCVCGuideBizListPage {
    NSInteger _userId; // 设备UD中保存的用户id，即当前用户id
    NSMutableArray<TSCJsonMsg *> * _jsonMsgArr; // 未读消息数组，从APP_DB中刷新
    BOOL _hasMoreData; // 是否还能从APP_DB获得更多数据
    
    // tableView相关
    UITableView * _tvBizList;
    TSCFragBtnGetMore * _fragBtnGetMore;
}


+ (id)vcGuideBizListPageWithStoryboardWithType:(TSCVCGuideBizListPageType)pageType {
    NSAssert(pageType == TSCVCGuideBizListPageTypeCustomerWantBuy || pageType == TSCVCGuideBizListPageTypeCustomerQ, @"[E]%s: 从Storyboard中初始化TSCVCGuideBizListPage时，传入了错误的pageType！", __FUNCTION__);
    
    UIStoryboard * sb = [UIStoryboard storyboardWithName:UI_STORYBOARD_NAME_MAIN bundle:[NSBundle mainBundle]];
    TSCVCGuideBizListPage * vc = (TSCVCGuideBizListPage *) [sb instantiateViewControllerWithIdentifier:UI_VC_NAME_GUIDE_BIZ_LIST_PAGE];
    vc.pageType = pageType;
    return vc;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 初始化类属性
    _userId = [[_ud objectForKey:UD_USER_ID] integerValue];
    _jsonMsgArr = [NSMutableArray array];
    _hasMoreData = NO;
    
    // 设置未读消息table
    _tvBizList = [[UITableView alloc]init];
    _tvBizList.rowHeight = 80.0f;
    _tvBizList.dataSource = self;
    _tvBizList.delegate = self;
    [self.view addSubview:_tvBizList];
    
    // 设置tvBizList的footerView
    _fragBtnGetMore = [[TSCFragBtnGetMore alloc]init];
    
    
    
    UIView * footerView = [[UIView alloc]init];
    footerView.frame = CGRectMake(0, 0, 0, 30.0f); // 指定footerView的高度
    [footerView addSubview:_fragBtnGetMore];
    _tvBizList.tableFooterView = footerView;
    
    // 约束
    // table
    _tvBizList.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_tvBizList]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_tvBizList)]];
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_tvBizList]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_tvBizList)]];
    // footerView
    _fragBtnGetMore.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_fragBtnGetMore]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_fragBtnGetMore)]];
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_fragBtnGetMore]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_fragBtnGetMore)]];
    
    // 注册观察者——当APP_DB中的未处理消息数量变化时
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshUnreadMsgList) name:NOTIFICATION_NAME_UNREAD_MSG_COME object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshUnreadMsgList) name:NOTIFICATION_NAME_UNREAD_MSG_DELETED object:nil];
    
    // 注册事件——“更多”按钮
    __weak typeof (self) _weakSelf = self;
    _fragBtnGetMore.btnClickListener = ^(UIButton * btn) {
        typeof (self) _strongSelf = _weakSelf;
        if (_strongSelf) {
            [_strongSelf getAppUnreadMsgList_P1:NO];
        }
    };
    
    
    // 搜索列表数据
    [self getAppUnreadMsgList_P1:YES];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark 公共方法
- (void) requery:(BOOL)isShowDialog {
    // 清理数据源
    [_jsonMsgArr removeAllObjects];
    
    // 清空table旧数据
    [_tvBizList reloadData];
    
    // 重新查询
    // 注：新的查询条件，应该在外部调用者那里设置好了
    [self getAppUnreadMsgList_P1:isShowDialog];
}

#pragma mark 私有方法
/* private */ - (void) setBtnGetMoreDisSearching {
    [_fragBtnGetMore setBtnEnabled:NO];
    [_fragBtnGetMore setBtnTitle:NSLocalizedString(@"btn_searching", nil) forState:UIControlStateDisabled];
}

/* private */ - (void) setBtnGetMoreDisHasData {
    [_fragBtnGetMore setBtnEnabled:YES];
    [_fragBtnGetMore setBtnTitle:NSLocalizedString(@"btn_get_more", nil) forState:UIControlStateNormal];
}

/* private */ - (void) setBtnGetMoreDisNoData {
    [_fragBtnGetMore setBtnEnabled:NO];
    [_fragBtnGetMore setBtnTitle:NSLocalizedString(@"btn_no_more", nil) forState:UIControlStateDisabled];
}

- (void) getAppUnreadMsgList_P1:(BOOL)isShowDialog {
    // 设置按钮及dialog显示
    [self setBtnGetMoreDisSearching];
    if (isShowDialog) {
        [self showDialogWithResourceKey:@"content_searching" isProcessing:YES];
    }
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 获得lv中最后一条消息的id
        NSInteger lastMsgId = [self getTvLastMsgId];
        
        NSArray<TSCJsonMsg *> * jsonMsgArr = nil;
        
        // 查询顾客求购未处理消息
        if (_pageType == TSCVCGuideBizListPageTypeCustomerWantBuy) {
            jsonMsgArr = [NSMutableArray arrayWithArray:[TSCMyDBUtil getUnreadMsgListWithUserId_1:_userId types:[NSString stringWithFormat:@"%li", DB_MSG_TYPE_CUSTOMER_WANT_BUY] lastMsgId:lastMsgId senderName:_queryCustomerName createDateStr:_queryDateStr isReaded:DB_ANY isFavorite:DB_ANY]];
        }
        // 查询顾客咨询未处理消息
        else {
            NSArray * typeArr =[NSArray arrayWithObjects:[NSNumber numberWithInteger:DB_MSG_TYPE_CUSTOMER_Q_IN_FIRST_REPLY], [NSNumber numberWithInteger:DB_MSG_TYPE_CUSTOMER_Q_IN_LIMIT_SELL], nil];
            
            jsonMsgArr = [NSMutableArray arrayWithArray:[TSCMyDBUtil getUnreadMsgListWithUserId_1:_userId types:[TSCMyUtil implodeWithGlue:@"," array:typeArr] lastMsgId:lastMsgId senderName:_queryCustomerName createDateStr:_queryDateStr isReaded:DB_ANY isFavorite:DB_ANY]];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self getAppUnreadMsgList_P2:jsonMsgArr];
        });
    });
}

- (void) getAppUnreadMsgList_P2:(NSArray *) jsonMsgArr {
    // 查询完毕后关闭提示框
    [self dissmisDialog];
    
    // 有返回待显示的数据
    if ([jsonMsgArr count] > 0) {
        [_jsonMsgArr addObjectsFromArray:jsonMsgArr];
        [_tvBizList reloadData];
        
        // 更新“更多”按钮显示
        [self setBtnGetMoreDisHasData];
        
        // 更新标识位
        _hasMoreData = YES;
    }
    // 某次查询未返回任何数据
    else {
        // “更多”按钮不可用
        [self setBtnGetMoreDisNoData];
        
        // 更新标识位
        _hasMoreData = NO;
    }
}

/**
 * 获得lv中最后一条JsonMsg的msgId
 *
 * @author Rio
 * @date 2014-11-30
 * @return 如果lv中没有记录，则返回0
 */
- (NSInteger) getTvLastMsgId {
    NSInteger count = [_jsonMsgArr count];
    if (count <= 0) {
        return 0;
    } else {
        return _jsonMsgArr[count - 1].msgId;
    }
}

#pragma mark UITableView及其代理的生命周期方法

// 获得总行数
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_jsonMsgArr count];
}

// 每一行内容是什么
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 创建cell
    static NSString *cellReuseId = @"textCell";
    TSCMyCellCommon *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseId];
    if (cell == nil) {
        cell = [[TSCMyCellCommon alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellReuseId];
    }
    
    // 获得view数据源
    TSCJsonMsg * jsonMsg = _jsonMsgArr[indexPath.row];
    
    // 获得“想买”/“想问”
    NSString * wantBuyOrWantQ;
    if (_pageType == TSCVCGuideBizListPageTypeCustomerWantBuy) {
        wantBuyOrWantQ = NSLocalizedString(@"content_want_buy", nil);
    } else {
        wantBuyOrWantQ = NSLocalizedString(@"content_want_q", nil);
    }
    
    // 更新view显示
    // （1）顾客头像
    [TSCMyUIUtil setUserPicIvWithUserPicUrl:jsonMsg.senderPicUrl imageView:cell.ivPic isUseDefaultPic:YES onSuccess:nil onFailure:nil];
    // （2）顾客姓名
    cell.lb1.text = jsonMsg.senderName;
    // （3）消息内容
    cell.lb2.text = [NSString stringWithFormat:@"%@%@", wantBuyOrWantQ, jsonMsg.info]; // 注：IOS中的lableView会自动根据显示长度加入...，不需要手工转换文字outline，这一点跟Android不同
    // （4）消息创建时间
    cell.lbTime.text = [TSCMyUtil getDateStrFromTs:jsonMsg.createTime format:@"MM月dd日\r\nHH点mm分"]; // \r\n表示换行
    
    
    // 注册事件——进入顾客空间界面
    cell.ivPic.userInteractionEnabled = YES;
    cell.ivPic.tag = jsonMsg.senderId; // 保存顾客id
    [cell.ivPic addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cellIvPicClicked:)]];
    
    // 注册事件——长按lv中的一项，显示删除对话框
    cell.tag = jsonMsg.msgId; // 保存msgId
    [cell addGestureRecognizer: [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(cellLongPressed:)]];
    
    return cell;
}

// 注册事件——进入顾客空间界面
- (void) cellIvPicClicked:(UITapGestureRecognizer *)recognizer {
    TSCVCCustomerSpace * vc = [TSCVCCustomerSpace vcCustomerSpaceWithStoryboard];
    [self.navigationController pushViewController:vc animated:YES];
    
    // VC间传递参数
    NSDictionary * inputDic = [NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:recognizer.view.tag] forKey:AEKI_CUSTOMER_ID];
    [[NSNotificationCenter defaultCenter] addObserver:vc selector:@selector(SELECTOR_GET_VC_INPUT) name:UI_VC_NAME_CUSTOMER_SPACE object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:UI_VC_NAME_CUSTOMER_SPACE object:inputDic];
}

// 注册事件——长按lv中的一项，显示删除对话框
- (void) cellLongPressed:(UITapGestureRecognizer *)recognizer {
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        
        UIAlertView * av = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"title_confirm_delete", nil) message:NSLocalizedString(@"title_confirm_del_this_unprocessed_msg", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"btn_cancel", nil) otherButtonTitles:NSLocalizedString(@"btn_confirm", nil), nil];
        av.tag = recognizer.view.tag;// 保存msgId
        [av show];
    }
}

// 注册事件——选择某行后
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 取消选中的状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // 注册事件——单击lv中的一项
    TSCJsonMsg * jsonMsg = _jsonMsgArr[indexPath.row];
    // 进入求购界面
    if (_pageType == TSCVCGuideBizListPageTypeCustomerWantBuy) {
        TSCVCCustomerWantBuyR * vc = [TSCVCCustomerWantBuyR vcCustomerWantBuyRWithStoryboard];
        [self.navigationController pushViewController:vc animated:YES];
        
        // VC间传递参数
        NSDictionary * inputDic = [NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:jsonMsg.msgId] forKey:AEKI_WANT_BUY_ID];
        [[NSNotificationCenter defaultCenter] addObserver:vc selector:@selector(SELECTOR_GET_VC_INPUT) name:UI_VC_NAME_CUSTOMER_WANT_BUY_R object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:UI_VC_NAME_CUSTOMER_WANT_BUY_R object:inputDic];
    }
    // 进入回复顾客咨询界面
    else {
        TSCVCReplyQA * vc = [TSCVCReplyQA vcReplyQAWithStoryboard];
        [self.navigationController  pushViewController:vc animated:YES];
        
        // VC间传递参数
        NSDictionary * inputDic = [NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:jsonMsg.msgId] forKey:AEKI_QA_ID];
        [[NSNotificationCenter defaultCenter] addObserver:vc selector:@selector(SELECTOR_GET_VC_INPUT) name:UI_VC_NAME_REPLY_QA object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:UI_VC_NAME_REPLY_QA object:inputDic];
    }
}

// 注册事件——自动获得更多
- (void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // 如果将要显示最后一行，并且后续APP_DB还可能返回数据
    if (indexPath.row == ([_jsonMsgArr count] - 1) && _hasMoreData == YES) {
        [self getAppUnreadMsgList_P1:NO];
    }
}

#pragma mark UIAlertViewDelegate
//根据被点击按钮的索引处理点击事件
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    // 0 == 取消
    if (buttonIndex == 0) {
        // do nothing
    }
    // 1 == 确定
    else if (buttonIndex == 1) {
        [TSCMyDBUtil deleteUnreadMsgWithMsgId_1:alertView.tag]; // 注：待删除消息id保存在alertView的tag上
    }
    
}

#pragma mark 观察者响应事件
- (void) refreshUnreadMsgList {
    // 从APP_DB中重新查询
    // 注：不显示“正在查询”提示
    [self requery:NO];
}

@end
